import { login, getUserinfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userInfo: {}
  },
  mutations: {
    updateToken(state, token) {
      state.token = token
      setToken(token)
    },
    updateUserInfo(state, val) {
      state.userInfo = val
    },
    removeUserinfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
      // 清空路由
      resetRouter()
    }
  },
  actions: {
    async getLoginToken(store, from) {
      const res = await login(from)
      // console.log(res)
      store.commit('updateToken', res)
    },
    async getUserInfo({ commit }) {
      const res = await getUserinfo()
      const res_ = await getUserDetailById(res.userId)
      commit('updateUserInfo', { ...res, ...res_ })
      return res
    }
  }
}
